//Copyright 2010 Balazs Keri, Imre Keri
//
//This file is part of FireworksCreator.
//
//FireworksCreator is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//FireworksCreator is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with FireworksCreator.  If not, see <http://www.gnu.org/licenses/>.
//
#include "modeldataobjectadapter.h"
#include "objectnameview.h"
#include "primitives.h"
#include "primitivegroup.h"
#include "ui_util.h"
//
ObjectNameView::ObjectNameView(QWidget *p_parent)
:
   QLineEdit(p_parent)
{
   setMaxLength(USER_NAME_MAX);
   connect(this,SIGNAL(editingFinished()),SLOT(on_editingFinished()));
}
ObjectNameView::~ObjectNameView()
{
}
//
void ObjectNameView::on_editingFinished()
{
   if(!isModified())
      return;
   ModelDataObjectAdapter *const adap=ModelDataObjectAdapter::get_adapter(get_object()->metaObject()->className());
   QScopedPointer<PrimitiveGroup> group(new PrimitiveGroup(get_document()));
   Primitives::SetDataObjectName *prim;
   group->set_description(tr("rename object '%1' to '%2'","commands").arg(adap->get_object_name(get_object())).arg(text()));
   try
   {
      group->add_exec(prim=new Primitives::SetDataObjectName(*adap,get_document(),get_object(),text()));
      group->finalize();
   }
   catch(UiError&)
   {
      return;
   }
   group.take();
}
//
void ObjectNameView::handle_object_changed(Identified *old_object)
{
   setEnabled(get_object()!=0);
   if(get_object())
      setText(ModelDataObjectAdapter::get_adapter(get_object()->metaObject()->className())->get_object_name(get_object()));
   else
      clear();
}
void ObjectNameView::handle_post_primitive(const Primitive &prim)
{
   using namespace Primitives;
   switch(prim.type)
   {
   case type_SetDataObjectName:
      {
         const SetDataObjectName& p=static_cast<const SetDataObjectName&>(prim);
         if(p.get_object_id()==get_object()->get_id())
            setText(p.get_adapter().get_object_name(get_object()));
      }
      break;
   }
}
